package com.keyinong.caizhengting.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author：郑谦
 * @时间：2017-4-10 下午4:02:27
 * @类名：LoginActivity.java
 * @功能: 登录
 */

public class LoginActivity extends Activity {
    /**
     * 登录
     */
    Button btn_login;
    /**
     * 注册账号
     */
    TextView tv_register;
    /**
     * 忘记密码
     */
    TextView tv_forget;
    /**
     * 手机号
     */
    private EditText et_phone;
    /**
     * 密码
     */
    private EditText et_password;
    /**
     * 再按一次退出
     */
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        setview();
        setaddListener();
    }

    private void setaddListener() {
        /**登录*/
        btn_login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//				Intent intent = new Intent();
//				intent.setClass(getApplicationContext(), FanqiedingcanActivity.class);
//				startActivity(intent);
                login();

            }


        });

        /**注册*/
        tv_register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), RegisterActivity.class);
                startActivity(intent);
            }
        });

        /**忘记密码*/
        tv_forget.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), ForgetpwdActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 登录
     */
    private void login() {
        if (NetWorkUtil.isNetwork(getApplicationContext()) == false) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        String phone = et_phone.getText().toString();
        String pwd = et_password.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            et_phone.setError("手机号为空");
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            et_password.setError("密码为空");
            return;
        }
        if (!TextUtils.isDigitsOnly(phone)) {
            et_phone.setError("请输入正确的手机号");
            return;
        }
        if (phone.length() != 11) {
            et_phone.setError("手机号不符");
            return;
        }
        HttpTools httptools = new HttpTools(getApplicationContext());
        httptools.login(phone, pwd, new JsonLogin());
    }

    private void setview() {
        btn_login = (Button) findViewById(R.id.btn_login);
        et_phone = (EditText) findViewById(R.id.et_name);
        et_password = (EditText) findViewById(R.id.et_pwd);
        tv_register = (TextView) findViewById(R.id.tv_registered);
        tv_forget = (TextView) findViewById(R.id.tv_forgetPwd);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class JsonLogin extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                Log.i("zq", response.toString());
                if (code == true) {
                    Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                    String data = response.getString("data");
                    Log.i("shi", data);
                    SharedPreferences spReg = getSharedPreferences("spReg",
                            Context.MODE_PRIVATE);
                    Editor editor = spReg.edit();
                    editor.putString("data", data);
                    editor.commit();

                    SharedPreferences spuser = getSharedPreferences("spuser",
                            Context.MODE_PRIVATE);
                    Editor editoruser = spuser.edit();
                    editoruser.putString("phone", et_phone.getText().toString());
                    editoruser.putString("pwd", et_password.getText().toString());
                    editoruser.commit();
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), FanqiedingcanActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}